package com.dolawing.phonecallapp.phonecallui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import android.os.PowerManager;
import android.provider.MediaStore;
import android.telecom.TelecomManager;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;


import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.dolawing.phonecallapp.ActivityStack;
import com.dolawing.phonecallapp.App;
import com.dolawing.phonecallapp.MainActivity;
import com.dolawing.phonecallapp.R;
import com.dolawing.phonecallapp.utils.AudioUtil;
import com.dolawing.phonecallapp.utils.PhoneUtil;

import java.util.Calendar;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import static com.dolawing.phonecallapp.listenphonecall.CallListenerService.formatPhoneNumber;


/**
 * 提供接打电话的界面，仅支持 Android M (6.0, API 23) 及以上的系统
 *
 * @author aJIEw
 */
@RequiresApi(api = Build.VERSION_CODES.M)
public class PhoneCallActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tvCallNumberLabel;
    private TextView tvCallNumber,tvCallNumberCarrier,tvCallNumberCity;
    private TextView tvPickUp;
    private TextView tvCallingTime;
    private TextView tvHangUp;
    private Switch switchRecordAudio; //录音

    private PhoneCallManager phoneCallManager;
    private PhoneCallService.CallType callType;
    private String phoneNumber;

    private Timer onGoingCallTimer;
    private int callingTime;

    public static void actionStart(Context context, String phoneNumber,
                                   PhoneCallService.CallType callType) {
        Intent intent = new Intent(context, PhoneCallActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Intent.EXTRA_MIME_TYPES, callType);
        intent.putExtra(Intent.EXTRA_PHONE_NUMBER, phoneNumber);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //保持屏幕常亮
        showOnLockScreen();

        setContentView(R.layout.activity_phone_call);

        ActivityStack.getInstance().addActivity(this);

        initData();

        initView();
    }

    private void initData() {
        phoneCallManager = new PhoneCallManager(this);
        onGoingCallTimer = new Timer();
        if (getIntent() != null) {
            phoneNumber = getIntent().getStringExtra(Intent.EXTRA_PHONE_NUMBER);
            callType = (PhoneCallService.CallType) getIntent().getSerializableExtra(Intent.EXTRA_MIME_TYPES);
        }
    }

    private void initView() {
        int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION //hide navigationBar
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
        getWindow().getDecorView().setSystemUiVisibility(uiOptions);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

        tvCallNumberLabel = findViewById(R.id.tv_call_number_label);
        tvCallNumber = findViewById(R.id.tv_call_number);
        tvCallNumberCarrier = findViewById(R.id.tv_call_number_carrier);
        tvCallNumberCity = findViewById(R.id.tv_call_number_city);
        tvPickUp = findViewById(R.id.tv_phone_pick_up);
        tvCallingTime = findViewById(R.id.tv_phone_calling_time);
        tvHangUp = findViewById(R.id.tv_phone_hang_up);
        switchRecordAudio = findViewById(R.id.switch_record_audio); //录音

        tvCallNumberCarrier.setText(PhoneUtil.getCarrier(phoneNumber,86));
        tvCallNumberCity.setText(PhoneUtil.getGeo(phoneNumber,86));
        tvCallNumber.setText(formatPhoneNumber(phoneNumber));
        tvPickUp.setOnClickListener(this);
        tvHangUp.setOnClickListener(this);

        switchRecordAudio.setOnClickListener(v -> {
            // 发起将本应用设为默认电话应用的请求，仅支持 Android M 及以上
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (switchRecordAudio.isChecked()) {

                    String audioName = DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA)) + ".mp3";
                    App.getInstance().setRecordAudioName(audioName); //存储录音文件名
                    AudioUtil.startRecordAudio(PhoneCallActivity.this, audioName);

                } else {
                    // 取消时跳转到默认设置页面
                   // startActivity(new Intent("android.settings.MANAGE_DEFAULT_APPS_SETTINGS"));
                    AudioUtil.stopRecordAudio(PhoneCallActivity.this);
                }
            } else {
                Toast.makeText(PhoneCallActivity.this, "Android 6.0 以上才支持修改默认电话应用！", Toast.LENGTH_LONG).show();
                switchRecordAudio.setChecked(false);
            }

        });


        // 打进的电话
        if (callType == PhoneCallService.CallType.CALL_IN) {
            tvCallNumberLabel.setText("来电号码");
            tvPickUp.setVisibility(View.VISIBLE);
        }
        // 打出的电话
        else if (callType == PhoneCallService.CallType.CALL_OUT) {
            tvCallNumberLabel.setText("呼叫号码");
            tvPickUp.setVisibility(View.GONE);
            phoneCallManager.openSpeaker();
        }

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_phone_pick_up) {
            phoneCallManager.answer();
            tvPickUp.setVisibility(View.GONE);
            tvCallingTime.setVisibility(View.VISIBLE);
            onGoingCallTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @SuppressLint("SetTextI18n")
                        @Override
                        public void run() {
                            callingTime++;
                            tvCallingTime.setText("通话中：" + getCallingTime());
                        }
                    });
                }
            }, 0, 1000);
        } else if (v.getId() == R.id.tv_phone_hang_up) {
            phoneCallManager.disconnect();
            stopTimer();
        }
    }

    private String getCallingTime() {
        int minute = callingTime / 60;
        int second = callingTime % 60;
        return (minute < 10 ? "0" + minute : minute) +
                ":" +
                (second < 10 ? "0" + second : second);
    }

    private void stopTimer() {
        if (onGoingCallTimer != null) {
            onGoingCallTimer.cancel();
        }

        callingTime = 0;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        phoneCallManager.destroy();
    }

    /**
     * 第一步：唤醒屏幕,保持进程不被睡眠
     */
    private PowerManager.WakeLock mWakeLock;
    /**
     * 获取了 SCREEN_DIM_WAKE_LOCK锁，该锁使CPU保持运转，屏幕保持亮度（可以变灰）
     * PowerManager.ACQUIRE_CAUSES_WAKEUP  一旦获得唤醒锁时，屏幕和键盘 就会立即 强制打开
     * PowerManager.SCREEN_DIM_WAKE_LOCK  屏幕保持点亮,DIM逐渐变暗,键盘关闭
     * PowerManager.SCREEN_BRIGHT_WAKE_LOCK  屏幕BRIGHT保持高亮,键盘关闭
     */
    private void acquireWakeLock() {
        if (mWakeLock ==null) {
            Log.i("Acquiring wake lock","获取wakeLock锁");
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, this.getClass().getCanonicalName());
            mWakeLock.acquire();
        }
    }

    /**
     * 释放wakeLock锁
     * 判断是否已经获取WakeLock： wakeLock.isHeld()
     */
    private void releaseWakeLock() {
        if (mWakeLock !=null&& mWakeLock.isHeld()) {
            Log.i("Acquiring wake unlock","释放wakeLock锁");
            mWakeLock.release();
            mWakeLock =null;
        }
    }
    /**
     * 唤醒屏幕:官方推荐
     */
    public void showOnLockScreen() {
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | //保持屏幕不息屏
                        WindowManager.LayoutParams.FLAG_FULLSCREEN |
                        WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | //锁屏显示
                        WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON,  //点亮屏幕
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
                        WindowManager.LayoutParams.FLAG_FULLSCREEN |
                        WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                        WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    }

    public void showOnLockScreen1(){
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN  //全屏
                |WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED //锁屏显示
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD //解锁屏幕
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON //保持屏幕不息屏
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);//点亮屏幕
    }

}
